/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OpenClient.java
 *
 * Created on 30 déc. 2010, 15:44:27
 */

package org.epsi.blokus.salon;

/**
 *
 * @author alex
 */
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.epsi.blokus.Hex;
import org.epsi.blokus.commun.Message;


public class GuiSalon extends javax.swing.JFrame implements Observer, ListSelectionListener{

    // Format de date
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");


    private ServerClient client;
    private Vector<String> dataRows;
   
    public GuiSalon(ServerClient c) {
        initComponents();
        client = c;

        // Liste des salons
        dataRows = new Vector<String>();
        this.liste.setListData(dataRows);

        this.liste.addListSelectionListener(this);

    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnRejoindre = new javax.swing.JButton();
        btnCreerSalon = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtChat = new javax.swing.JTextArea();
        btnEnvoyer = new javax.swing.JButton();
        txtMessage = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        liste = new javax.swing.JList();
        btnSortie = new javax.swing.JButton();
        btnEntrainement = new javax.swing.JToggleButton();
        txtNbJoueurs = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Serveurs de JEU");
        setMinimumSize(new java.awt.Dimension(574, 344));

        btnRejoindre.setText("Rejoindre salon");
        btnRejoindre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRejoindreActionPerformed(evt);
            }
        });

        btnCreerSalon.setText("Créer salon");
        btnCreerSalon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreerSalonActionPerformed(evt);
            }
        });

        txtChat.setColumns(20);
        txtChat.setEditable(false);
        txtChat.setRows(5);
        jScrollPane1.setViewportView(txtChat);

        btnEnvoyer.setText("Envoyer");
        btnEnvoyer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEnvoyerActionPerformed(evt);
            }
        });

        txtMessage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMessageActionPerformed(evt);
            }
        });

        liste.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(liste);

        btnSortie.setText("Sortir du salon");
        btnSortie.setEnabled(false);
        btnSortie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSortieActionPerformed(evt);
            }
        });

        btnEntrainement.setText("Entrainement (IA)");
        btnEntrainement.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEntrainementActionPerformed(evt);
            }
        });

        txtNbJoueurs.setEditable(false);

        jLabel1.setText("Nbr joueurs");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEnvoyer, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 291, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtNbJoueurs)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnEntrainement, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnSortie, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                            .addComponent(btnRejoindre, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                            .addComponent(btnCreerSalon, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnCreerSalon, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnRejoindre, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnSortie, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnEntrainement, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtNbJoueurs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEnvoyer, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(txtMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Sélection d'un salon
     * @param e
     */
    public void valueChanged(ListSelectionEvent e) {
           
        String nomSalon = (String) liste.getSelectedValue();

        // Récupère l'ID du salon
        StringTokenizer stringToken = new StringTokenizer(nomSalon);
        String ID = stringToken.nextToken();

        // Envoie message de demande du nombre de joueurs
        client.envoyer(
                new Message(Message.TTypeMessage.requete_nb_joueurs)
                .addObject("IDSALON", ID)
        );

    }

    /**
     * Rejoindre un salon
     * @param evt
     */
    private void btnRejoindreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRejoindreActionPerformed

        Message m = new Message();
        String Selection = (String)this.liste.getSelectedValue();
        StringTokenizer stringToken = new StringTokenizer(Selection);
        String ID = stringToken.nextToken();
        m.setTypeMessage(Message.TTypeMessage.entrer_salon).addObject("IDSALON",Integer.parseInt(ID));
        client.envoyer(m);
                
    }//GEN-LAST:event_btnRejoindreActionPerformed

    /**
     * Envoyer un message sur le chat
     * @param evt
     */
    private void btnEnvoyerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnvoyerActionPerformed
        envoyerLigneChat();
    }//GEN-LAST:event_btnEnvoyerActionPerformed

    /**
     * Créer un nouveua salon
     * @param evt
     */
    private void btnCreerSalonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreerSalonActionPerformed
      client.creationSalon();
      this.setEnabled(false);
    }//GEN-LAST:event_btnCreerSalonActionPerformed

    /**
     * Quitter un salon
     * @param evt
     */
    private void btnSortieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSortieActionPerformed
        Message m = new Message();
        String Selection = (String)this.liste.getSelectedValue();
        StringTokenizer stringToken = new StringTokenizer(Selection);
        String ID = stringToken.nextToken();

        m.setTypeMessage(Message.TTypeMessage.sortir_salon).addObject("IDSALON",Integer.parseInt(ID));
        client.envoyer(m);

        this.btnRejoindre.setEnabled(true);
        this.btnSortie.setEnabled(false);
    }//GEN-LAST:event_btnSortieActionPerformed

    /**
     * Envoyer message sur le chat
     * @param evt
     */
    private void txtMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMessageActionPerformed
        envoyerLigneChat();
    }//GEN-LAST:event_txtMessageActionPerformed

    /**
     * Lancer une partie d'entrainement
     * @param evt
     */
    private void btnEntrainementActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntrainementActionPerformed
        Hex.getInstance().newTrainingGame();
    }//GEN-LAST:event_btnEntrainementActionPerformed

    /**
     * Gestion des message reçus
     * @param o : Source
     * @param m : Message
     */
    public void update(Observable o, Object m) {
        Message mess = (Message)m;


        switch(mess.getTypeMessage())
        {

            // Réception d'un message chat
            case chat_salon_recevoir:
                String txt = (String)mess.getObject("Message");
                String src = (String)mess.getObject("Source");
                this.addLineRecu(src+" > "+txt);
            break;


            // Connexion réussie
            // Mise à jour de la liste des salons
            case connexion_client_ack:
            case maj_liste_salons:
                clearLineSalon();
                ArrayList<String> list  = (ArrayList<String>) mess.getObject("LISTSALONS");
                for (String line : list) addLineSalon(line);
            break;

            // Nouveau salon ouvert
            case ouverture_salon:
                String idSalon = (String)mess.getObject("IDSALON");
                String nomSalon = (String)mess.getObject("NOMSALON");
                String nomMaitre = (String)mess.getObject("MAITRE");
              
                this.addLineSalon(idSalon + " "+ nomSalon +  " par "+nomMaitre);
            break;

            // Entrée dans un salon réussie
            case entrer_salon_ack:
                 String salonSelectionne = (String)mess.getObject("IDSALON");
                 if (salonSelectionne!=null) this.addLineRecu("Connexion au salon "+ salonSelectionne);
                 
                 this.btnRejoindre.setEnabled(false);
                 this.btnSortie.setEnabled(true);
            break;

            // Impossible d'entrer dans le salon
            case entrer_salon_err:
                 String erreur = (String)mess.getObject("ERREUR");
                 JOptionPane.showMessageDialog(this, erreur, "Impossible de rejoindre le salon", JOptionPane.ERROR_MESSAGE);
            break;

            // Fermer salon
            case fermeture_salon_ack:
                 this.addLineRecu("Fermeture du salon");
                 this.setEnabled(true);
            break;

            // Ejecté d'un salon
            case salon_fermeture_prematuree:
                JOptionPane.showMessageDialog(this, "Le salon auquel vous étiez connecté a été fermé !", "Avertissement", JOptionPane.INFORMATION_MESSAGE);

                this.btnRejoindre.setEnabled(true);
                this.btnSortie.setEnabled(false);
            break;

            // Mise à jour du nombre de joueurs
            case reponse_nb_joueurs:

                Integer nb = (Integer)mess.getObject("NB");
                this.txtNbJoueurs.setText(nb.toString());

            break;

            // Lancement d'une partie
            case lancer_partie:
                 //Hex.getInstance().newOnlineGame(this.client, false);
                 java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
                //Hex h = new Hex();
                //h.newOnlineGame(client, false);
            Hex.getInstance().newOnlineGame(client, false);
                 }});
            break;

        }

        
    }

    /**
     * Ligne de chat envoyée
     * @param str
     */
    public void envoyerLigneChat()
    {
        if (this.txtMessage.getText().length()>0)
        {
            Date now = new Date();
            String str = this.txtMessage.getText();

            // Mise à jour du chat
            this.txtChat.setText(this.txtChat.getText()+"["+dateFormat.format(now)+"]  "+str+"\n");

            // Envoie du message
            Message m = new Message();
            m.setTypeMessage(Message.TTypeMessage.chat_salon_poster).addObject("Message",this.txtMessage.getText());
            client.envoyer(m);

            // RAZ du champs message
            this.txtMessage.setText("");
        }
    }


    /**
     * Ligne de chat reçue
     * @param str
     */
    public void addLineRecu(String str)
    {
        Date now = new Date();
        this.txtChat.setText(this.txtChat.getText()+"["+dateFormat.format(now)+"]  "+str+"\n");
    }

     /**
      * Ajoute une ligne à la liste des salons
      * @param txt
      */
    private void addLineSalon(String txt) {
        dataRows.add(txt);
        this.liste.setListData(dataRows);
        this.liste.doLayout();
    }

    private void clearLineSalon()
    {
        dataRows.clear();
        this.liste.setListData(dataRows);
        this.liste.doLayout();
    }
   

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCreerSalon;
    private javax.swing.JToggleButton btnEntrainement;
    private javax.swing.JButton btnEnvoyer;
    private javax.swing.JButton btnRejoindre;
    private javax.swing.JButton btnSortie;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    protected javax.swing.JList liste;
    private javax.swing.JTextArea txtChat;
    private javax.swing.JTextField txtMessage;
    private javax.swing.JTextField txtNbJoueurs;
    // End of variables declaration//GEN-END:variables






    

}
